﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Jemgine.MapEditor
{
    [Tools.SelectableTool]
    public class RotateBoneTool : BaseBoneTool
    {
        class BoneRotateHook : Data.Rotatable
        {
            Data._BonePosition Bone;
            public BoneRotateHook(Data._BonePosition Bone) { this.Bone = Bone; }


            public object PrepareToRotate()
            {
                return Bone.Angle;
            }

            public void ApplyRotation(object Tag, float Rotation)
            {
                float OriginalAngle = (float)Tag;
                Bone.Angle = OriginalAngle + Rotation;
            }

            public void Snap(Data.Snapper Snapper)
            { }
        }

        Object TransformationTag;
        Data.Rotatable Rotatable;
        Vector2 MouseDelta;
        bool Changes = false;

        public override System.Drawing.Image GetIcon() { return System.Drawing.Image.FromFile("ToolIcons/rotatebone.bmp"); }

        public override void MouseDown(MouseInputState InputState, EditorState EditorState)
        {
            if (EditorState.Selected.Type != Engine.Selection.Types.Vertex) return;
            var Skeleton = EditorState.GetMiddleObject(EditorState.Selected) as Data.Skeleton;
            if (Skeleton == null) return;

            if ((InputState.Modifiers & System.Windows.Forms.Keys.Control) == System.Windows.Forms.Keys.Control)
                SelectBone(InputState.Position, Skeleton, EditorState);
            else
            {
                var Bone = Skeleton.GetBone(EditorState.Selected.BottomIndex);
                Data._BonePosition BonePosition = Skeleton.KeyFrames[EditorState.Selected.BottomIndex, Skeleton.EditorFrame];
                Rotatable = new BoneRotateHook(BonePosition);
                TransformationTag = Rotatable.PrepareToRotate();

                MouseDelta = Vector2.Zero;
                Changes = false;
            }
        }

        public override void MouseUp(MouseInputState InputState, EditorState EditorState)
        {
            if (Changes && Rotatable != null)
                EditorState.PerformOperation(new Operations.Rotate(Rotatable, MouseDelta.Y, TransformationTag,
                    (InputState.Modifiers & System.Windows.Forms.Keys.Alt) == System.Windows.Forms.Keys.Alt));
            Rotatable = null;
        }

        public override void MouseMove(MouseInputState InputState, EditorState EditorState)
        {
            MouseDelta += InputState.Delta;
            if (Rotatable != null) Rotatable.ApplyRotation(TransformationTag, MouseDelta.Y);
            Changes = true;
        }
    }
}
